package com.saikuo.service.dao.impl;

import com.saikuo.service.dao.IStoreInfoDao;
import com.saikuo.service.model.StoreInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.util.List;

/**
 * Created by shanchangyu on 16/10/13.
 */
@Repository
public class StoreInfoDaoImpl extends JdbcDaoSupport implements IStoreInfoDao {
    private static final BeanPropertyRowMapper<StoreInfo> mapper =
            new BeanPropertyRowMapper<>(StoreInfo.class);

    @Autowired
    StoreInfoDaoImpl(DataSource dataSource) {
        setDataSource(dataSource);
    }


    private static final String UPDATE_STORE_INFO = " update y_store_info set name=?,address=?,lat=?,lng=?,city_code=?,area_code=?,mobile=?,phone=? where store_code=?";

    @Override
    public boolean updateStoreInfo(String storeCode, String name, String address, Double lat, Double lng, String cityCode, String areaCode, String mobile, String phone) {
        return 1 == this.getJdbcTemplate().update(UPDATE_STORE_INFO, new Object[]{name, address, lat, lng, cityCode, areaCode, mobile, phone, storeCode});
    }


    private static final String GET_STORE_INFO_BY_STORE_CODE = "select * from y_store_info where store_code = ?";

    @Override
    public StoreInfo getStoreInfoByStoreCode(String storeCode) {
        List<StoreInfo> result = this.getJdbcTemplate().query(GET_STORE_INFO_BY_STORE_CODE,
                new Object[]{storeCode}, mapper);
        if (CollectionUtils.isNotEmpty(result)) {
            return result.get(0);
        }
        return null;
    }

    private static final String STORE_CODE_EXIST = "select count(*) from y_store_info where store_code=?";

    @Override
    public boolean storeCodeExist(String storeCode) {
        return 1 == this.getJdbcTemplate().queryForObject(STORE_CODE_EXIST,
                new Object[]{storeCode}, Integer.class);
    }

    @Override
    public List<StoreInfo> getStoresByUserLocationCode(String cityCode, String areaCode) {
        List<StoreInfo> areaResult = null, cityResult = null;
        if (areaCode != null) {
            areaResult = this.getJdbcTemplate().query("select * from y_store_info where area_code=? ", new Object[]{areaCode}, mapper);
        }
        if (cityCode != null) {
            cityResult = this.getJdbcTemplate().query("select * from y_store_info where city_code=? ", new Object[]{cityCode}, mapper);
        }
        if (CollectionUtils.isNotEmpty(areaResult)) {
            return areaResult;
        } else if (CollectionUtils.isNotEmpty(cityResult)) {
            return cityResult;
        }
        return null;
    }


}
